package com.lx.chong.controller;

import com.alibaba.fastjson.JSONObject;
import com.lx.chong.common.Result;
import com.lx.chong.dto.DepDto;
import com.lx.chong.dto.PageAndSortDto;
import com.lx.chong.dto.UserDto;
import com.lx.chong.enums.ResultEnum;
import com.lx.chong.form.DepartmentForm;
import com.lx.chong.form.UserForm;
import com.lx.chong.model.Department;
import com.lx.chong.model.User;
import com.lx.chong.service.impl.DepartmentServiceImpl;
import com.lx.chong.service.impl.UserServiceImpl;
import com.lx.chong.utils.MD5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author: chong
 * @date: 2018/8/23
 */
@Slf4j
@Api(description = "部门API")
@RestController
public class DepartmentController {

    @Autowired
    DepartmentServiceImpl departmentService;


    @ApiOperation(value = "分页获取部门")
    @PostMapping("/getDepartmentListPage")
    public Result getUserListPage(@RequestBody PageAndSortDto dto) {
        Result result = new Result();
        try {
            Page<Department> departmentList = departmentService.getDepListPage(dto);
            result.setData(departmentList);
        } catch (Exception e) {
            result.setCode(ResultEnum.OPERATION_ERROR.getCode());
            log.error(e.getMessage());
        }
        return result;
    }

    /**
     * 获取部门
     *
     * @return
     */
    @ApiOperation(value = "获取部门")
    @GetMapping("/getDepartmentSelect")
    public Result getUserListPage() {
        Result result = new Result();
        try {
            List<Department> departmentList = departmentService.findAllByIfDeleteAndUseMark();
            result.setData(departmentList);
        } catch (Exception e) {
            result.setCode(ResultEnum.OPERATION_ERROR.getCode());
            log.error(e.getMessage());
        }
        return result;
    }

    /**
     * 保存部门信息
     *
     * @param departmentForm
     * @return
     */
    @ApiOperation(value = "保存部门信息")
    @PutMapping("/saveDepartment")
    public Result saveDepartment(@RequestBody DepartmentForm departmentForm) {
        Result result = new Result();
        Department department = new Department();
        try {
            BeanUtils.copyProperties(departmentForm, department);
            if (department.getId() == null) {
                department.setAddDateTime(new Date());
            } else {
                Department one = departmentService.findOne(department.getId());
                department.setAddDateTime(one.getAddDateTime());
            }
            Department save = departmentService.save(department);
            result.setData(save);
        } catch (Exception e) {
            result.setCode(ResultEnum.OPERATION_ERROR.getCode());
            result.setMsg("保存用户信息异常");
            log.error(e.getMessage());
        }
        return result;
    }

    /**
     * 根据id获取对象
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id获取对象")
    @PostMapping("/getDepById")
    public Result getDepById(@RequestBody Long id) {
        Result result = new Result();
        try {
            Department department = departmentService.findOne(id);
            result.setData(department);
        } catch (Exception e) {
            result.setCode(ResultEnum.OPERATION_ERROR.getCode());
            result.setMsg("根据id获取对象异常");
            log.error(e.getMessage());
        }
        return result;
    }

    /**
     * 删除部门
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除部门")
    @PostMapping("/deleteDep")
    public Result deleteUser(@RequestBody Long id) {
        Result result = new Result();
        try {
            Department department = departmentService.findOne(id);
            department.setIfDelete(1);
            Department save = departmentService.save(department);
            result.setData(save);
        } catch (Exception e) {
            result.setCode(ResultEnum.OPERATION_ERROR.getCode());
            result.setMsg("删除用户");
            log.error(e.getMessage());
        }
        return result;
    }

    /**
     * 获取部门列表
     *
     * @param dto
     * @return
     */
    @PostMapping("/getDepListPage")
    public Result getDepListPage(@RequestBody DepDto dto) {
        Result result = new Result();
        try {
            List<Department> depListPage = departmentService.getDepListPage(dto.getPage(), dto.getSize());
            Long totalPage = departmentService.getDepCount();
            Page<Department> page = new PageImpl(depListPage, null, totalPage);
            result.setData(page);
        } catch (Exception e) {
            result.setCode(ResultEnum.OPERATION_ERROR.getCode());
            log.error(e.getMessage());
        }
        return result;
    }


    /**
     * 启用禁用
     *
     * @param object
     * @return
     */
    @ApiOperation(value = "启用禁用")
    @PostMapping("/changeDepMark")
    public Result changeDepMark(@RequestBody JSONObject object) {
        Result result = new Result();
        try {
            Long id = object.getLong("id");
            Integer status = object.getInteger("status");
            Department one = departmentService.findOne(id);
            one.setUseMark(status == 1 ? 0 : 1);
            Department save = departmentService.save(one);
            result.setData(save);
        } catch (Exception e) {
            result.setCode(ResultEnum.OPERATION_ERROR.getCode());
            result.setMsg("启用禁用");
            log.error(e.getMessage());
        }
        return result;
    }

    /**
     *  部门名称判重
     * @param department
     * @return
     */
    @PostMapping("/checkDepName")
    @Transactional(rollbackFor = Exception.class)
    public Result checkRepeat(@RequestBody Department department) {
        Result result = new Result();
        if (department.getName() == null) {
            log.error("[重复校验][{}:{}]:{}", ResultEnum.PARAM_ERROR.getMessage());
            result.setCode(ResultEnum.PARAM_ERROR.getCode());
            return result;
        }
        Map<String, Object> checkMap = new HashMap<>(Collections.emptyMap());
        checkMap.put("name", department.getName());
        boolean repeat = departmentService.checkRepeat("Department", checkMap, department.getId());
        log.info("部门名称判重", repeat);
        return result;
    }
}
